import { defineConfig, loadEnv } from 'vite'
import path from 'path'
// import { fileURLToPath, URL } from 'node:url'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
import AutoImport from 'unplugin-auto-import/vite'
import tailwindcss from 'tailwindcss'
import autoprefixer from 'autoprefixer'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
const baseUrl = 'http://localhost:8080' // 后端接口
export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd())
  const { VITE_APP_ENV } = env

  return {
    base: VITE_APP_ENV === 'production' ? '/' : '/',
    plugins: [
      vue(),
      Components({
        resolvers: [
          AntDesignVueResolver({
            importStyle: false,
          }),
        ],
      }),
      AutoImport({
        imports: ['vue', 'vue-router', 'vuex'],
        dts: 'src/auto-imports.d.ts',
      }),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(__dirname, 'src/assets/icons/svg')],
        symbolId: 'icon-[name]',
        inject: 'body-first',
      }),
    ].filter(Boolean),
    resolve: {
      alias: {
        '~': path.resolve(__dirname, './'),
        '@': path.resolve(__dirname, './src'),
      },
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
    },
    // vite 相关配置
    server: {
      port: 80,
      host: true,
      open: true,
      proxy: {
        // https://cn.vitejs.dev/config/#server-proxy
        '/dev-api': {
          target: baseUrl,
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/dev-api/, ''),
        },
        // springdoc proxy
        '^/v3/api-docs/(.*)': {
          target: baseUrl,
          changeOrigin: true,
        },
      },
    },
    // server: {
    //   port: 80,
    //   host: true,
    //   open: true,
    //   proxy: {
    //     '/api': {
    //       changeOrigin: true,
    //       rewrite: (path) => path.replace(/^\/api/, ''),
    //       // mock代理目标地址
    //       // target: 'http://127.0.0.1:8090/service/api',
    //       // target: 'http://192.168.147.238:9000',
    //       // target: 'http://192.168.136.167:8088',

    //       // 刁
    //       // target: 'http://192.168.144.131:8088',
    //       // 谭
    //       target: 'http://192.168.152.139:8095',
    //       ws: true,
    //     },
    //   },
    // },
    css: {
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove()
                }
              },
            },
          },
          tailwindcss, // 使用 import 引入的 tailwindcss
          autoprefixer, // 使用 import 引入的 autoprefixer
        ],
        config: {
          path: './postcss.config.js',
        },
      },
    },
  }
})
